package com.sk.orm.extend;

import com.sk.util.StringUtil;
import jakarta.persistence.AttributeConverter;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author smy
 * {@code @date} 2024/7/3
 */
public abstract class BaseDBConvertList<T> implements AttributeConverter<List<T>, String> {

    private final Function<String, T> db2entity;
    private final Function<T, String> entity2db;


    public BaseDBConvertList(Function<String, T> db2entity) {
        this.db2entity = db2entity;
        this.entity2db = String::valueOf;
    }

    public BaseDBConvertList(Function<String, T> db2entity, Function<T, String> entity2db) {
        this.db2entity = db2entity;
        this.entity2db = entity2db;
    }

    @Override
    public final String convertToDatabaseColumn(List<T> lists) {
        return !CollectionUtils.isEmpty(lists) ? StringUtil.join(",", lists.stream().map(entity2db).toArray()) : null;
    }

    @Override
    public final List<T> convertToEntityAttribute(String s) {
        return StringUtils.hasText(s) ? Arrays.stream(s.split(",")).map(db2entity).collect(Collectors.toList()) : new ArrayList<>();
    }
}
